// pages/map/mapTrace/mapTrace.js
import config from '../../../config.js';
var util = require('../../../utils/util.js');
//qqmap-wx-jssdk.min.js
// 引入SDK核心类
var QQMapWX = require('../../components/qqmap-wx-jssdk.min.js');
const base = config;
var app = getApp();
var that2;
var flag = false;


// 实例化API核心类
var map = new QQMapWX({
  key: 'D2KBZ-BTFHF-PNCJN-NFUUW-K4G56-DNFBW' // 必填
});

function getlocation() {
  var lat, lng;
  wx.getLocation({
    type: 'gcj02',
    success: function(res) {
      console.log(res);
      lat = res.latitude;
      lng = res.longitude;

      that2.reverseGeocoder(lat, lng)
    }
  });


}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    polyline: [],
    flag: flag,
    timer: null,
    orderId: null,
    type: 1,
    resume_bg: "https://app.longchg.com/gudongcar/images/resume_bg.png",
    start_bg: "https://app.longchg.com/gudongcar/images/start_bg.png",
    key: "D2KBZ-BTFHF-PNCJN-NFUUW-K4G56-DNFBW",
    height: wx.getSystemInfoSync().windowHeight, // 获取当前窗口的高度,
    loc: {
      from: null,
      to: null
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that2 = this;

    var orderId = options.orderId;
    var type = options.type;

    if (orderId != null && type != null) {
      this.setData({
        orderId: orderId,
        type: type,
      })
    }

    that2.loadPoylineData();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  loadPoylineData: function() {
    var that = this;
    //获取支付项目
    wx.request({
      url: base.getPoyline,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        orderId: that.data.orderId,
        index: that.data.type
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          if (res.data.data != null) {
            that.setData({
              paths: res.data.data
            })

            var points = [];
            var pickPath = that.data.paths.pickPath;
            if (pickPath!=null && pickPath.length > 0) {
              //将解压后的坐标放入点串数组pl中
              var pl = [];
              for (var i = 0; i < pickPath.length; i++) {
                var item = pickPath[i];
                that2.setData({
                  "loc.from.lat": item.lat,
                  "loc.from.lng": item.lng,
                  "loc.from.address": item.address,
                })
              }
            }



            var sendPath = that.data.paths.sendPath;
            if (pickPath != null && sendPath.length > 0) {
              //将解压后的坐标放入点串数组pl中
              var pl = [];
              for (var i = 0; i < sendPath.length; i++) {
                var item = sendPath[i];
                that2.setData({
                  "loc.to.lat": item.lat,
                  "loc.to.lng": item.lng,
                  "loc.to.address": item.address,
                })
              }
              that2.driving();
            }



          } else {
            getlocation();
          }

        } else {
          getlocation();
        }
      }

    })
  },
  //事件回调函数
  driving: function() {
    var _this = this;
    var key = _this.data.key;

    var from = "" + _this.data.loc.from.lat + "," + _this.data.loc.from.lng;
    var to = "" + _this.data.loc.to.lat + "," + _this.data.loc.to.lng;

    var url = 'https://apis.map.qq.com/ws/direction/v1/driving/?from=' + from + '&to=' + to + '&key=' + key;

    // console.log(url);
    //网络请求设置
    var opt = {
      //WebService请求地址，from为起点坐标，to为终点坐标，开发key为必填
      url: url,
      method: 'GET',
      dataType: 'json',
      //请求成功回调
      success: function(res) {
        console.log(res);
        var ret = res.data
        if (ret.status != 0) return; //服务异常处理
        var coors = ret.result.routes[0].polyline,
          pl = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({
            latitude: coors[i],
            longitude: coors[i + 1]
          })
        }
        //设置polyline属性，将路线显示出来
        var color = that2.data.type == 1 ? "#FF0000DD" : "#137af0";
        _this.setData({
          polyline: [{
            points: pl,
            color: color,
            width: 4
          }],
          markers: [{
              id: "1",
              latitude: _this.data.loc.from.lat,
              longitude: _this.data.loc.from.lng,
              width: 40,
              height: 40,
              iconPath: "../../../image/mstart.png",
              title: "起点"
            },
            {
              id: "2",
              latitude: _this.data.loc.to.lat,
              longitude: _this.data.loc.to.lng,
              width: 40,
              height: 40,
              iconPath: "../../../image/mend.png",
              title: "终点"
            }
          ]
        })
      }
    };
    wx.request(opt);
  },

  choosemap: function(e) {
    var type = e.currentTarget.dataset.index;
    var that = this;

    util.checkLocationIsOff(this)
    wx.chooseLocation({
      success: function(res) {
        console.log(res);
        if (type == 1) {
          that.setData({
            "loc.from.lat": res.latitude,
            "loc.from.lng": res.longitude,
            "loc.from.address": res.address,
          })
        } else {
          that.setData({
            "loc.to.lat": res.latitude,
            "loc.to.lng": res.longitude,
            "loc.to.address": res.address,
          })
        }
        if (that.data.loc.to != null) {
          that.driving();
        }


        //上传数据
        var index = that2.data.type=="1"?1:3;
        var num = index > 1 ? index + Number(type) - 1 : type;
        that2.setUploadPar(num, res.latitude, res.longitude, res.address);
      },
    })


  },
  setUploadPar: function(type, latitude, longitude, address) {
    var par = {};
    par.orderId = that2.data.orderId;
    par.type = type;
    par.point = [{
      latitude: latitude,
      longitude: longitude,
      address: address
    }]
    that2.uploadPoyline(par);
  },
  reverseGeocoder: function(latitude, longitude) {
    var that = this;
    // 调用接口
    map.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function(res) {
        console.log(res);
      },
      fail: function(res) {
        console.log(res);
      },
      complete: function(res) {
        if (res.result != null) {
          var address = res.result.address;
          console.log(address);
          that.setData({
            "loc.from.lat": latitude,
            "loc.from.lng": longitude,
            "loc.from.address": address,
          })
          that2.setUploadPar(that.data.type, latitude, longitude, address);
        }
      }
    });
  },

  uploadPoyline: function(par) {
    var that = this;
    var sessionId = wx.getStorageSync("session");
    wx.request({
      url: base.uploadPoyline,
      header: {
        'content-type': 'application/json',
        'Cookie': sessionId
      },
      data: {
        orderId: par.orderId,
        type: par.type,
        point: par.point,
      },
      success: function(res) {
        console.log(res.data);
      },
      fail: function() {
        console.log("111");
        wx.hideLoading();
      }
    })
  },
})